package com.fiberhome.nas.core.network.di

import android.content.Context
import coil.ImageLoader
import coil.disk.DiskCache
import coil.memory.MemoryCache
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.fiberhome.nas.core.network.BuildConfig
import com.fiberhome.nas.core.network.interceptor.AuthInterceptor
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    // 使用BuildConfig中的BASE_URL替换硬编码值
    private const val BASE_URL = BuildConfig.BASE_URL
//    private val BASE_URL = ""

    // 配置Json序列化
    @Provides
    @Singleton
    fun provideJson(): Json = Json {
        ignoreUnknownKeys = true
        coerceInputValues = true
        isLenient = true
//        encodeDefaults = true
    }

    // 提供OkHttpClient
    @Provides
    @Singleton
    fun provideOkHttpClient(
        authInterceptor: AuthInterceptor,
        loggingInterceptor: HttpLoggingInterceptor,
        dynamicUrlInterceptor: DynamicUrlInterceptor,
        @ApplicationContext context: Context
    ): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS) // 连接超时时间
            .writeTimeout(10, TimeUnit.SECONDS) // 写超时时间
            .readTimeout(10, TimeUnit.SECONDS) // 读超时时间
            .addInterceptor(authInterceptor)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(dynamicUrlInterceptor)
            .apply {
                if (BuildConfig.DEBUG) {
                    addInterceptor(ChuckerInterceptor.Builder(context).build())
                }
            }
            // 请求失败重试
            .retryOnConnectionFailure(true)
            .build()
    }

    // 提供Retrofit实例
    @Provides
    @Singleton
    fun provideRetrofit(
        okHttpClient: OkHttpClient,
        json: Json
    ): Retrofit {
        val contentType = "application/json".toMediaType()
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(json.asConverterFactory(contentType))
            .build()
    }

    // 添加这个提供HttpLoggingInterceptor的方法
    @Provides
    @Singleton
    fun provideLoggingInterceptor(): HttpLoggingInterceptor {
        return HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor.Level.BODY
            } else {
                HttpLoggingInterceptor.Level.NONE
            }
        }
    }

    // 提供动态URL拦截器
    @Provides
    @Singleton
    fun provideDynamicUrlInterceptor(networkManager: NetworkManager): DynamicUrlInterceptor {
        return DynamicUrlInterceptor(networkManager)
    }

    // 提供NetworkManager
    @Provides
    @Singleton
    fun provideNetworkManager(@ApplicationContext context: Context): NetworkManager {
        return NetworkManager(context)
    }

    // 提供Coil ImageLoader
    @Provides
    @Singleton
    fun provideImageLoader(
        @ApplicationContext context: Context,
        okHttpClient: OkHttpClient
    ): ImageLoader {
        return ImageLoader.Builder(context)
            .okHttpClient { okHttpClient }
            .memoryCache {
                MemoryCache.Builder(context)
                    .maxSizePercent(0.25) // 使用应用内存的25%
                    .build()
            }
            .diskCache {
                DiskCache.Builder()
                    .directory(context.cacheDir.resolve("coil_cache")) // 缓存目录
                    .maxSizeBytes(512L * 1024 * 1024) // 512MB缓存大小
                    .build()
            }
            .crossfade(true)
            .build()
    }
}

// 添加动态URL拦截器类
class DynamicUrlInterceptor(private val networkManager: NetworkManager) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        // 获取动态baseURL
        val baseUrl = runBlocking {
            networkManager.getBaseUrl()
        }
        networkManager.baseUrl = baseUrl
        // 构建新的请求URL
        val parsedUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalArgumentException("Invalid URL")
        val newUrl = originalRequest.url.newBuilder()// 1. 创建URL构建器
            .scheme(parsedUrl.scheme)// 2. 设置协议为HTTP
            .host(parsedUrl.host)// 3. 设置主机名
            .port(parsedUrl.port)
            .build()// 4. 构建新URL
        // 构建新的请求
        val newRequest = originalRequest.newBuilder()
            .url(newUrl)
            .build()
        // 继续处理请求
        return chain.proceed(newRequest)
    }
}